<?php

class Pageouter {

    const UNLIMITED = '-1';

    /**
     * @var Diapasone
     */
    private $oDiapasone;

    private $itemsOnPage;
    private $totalItems;
    private $currentPage;

    private function getDefaultItemsOnPage() {
        return 5;
    }

    private function __construct($currentPage, $itemsOnPage) {

        if ($itemsOnPage < 1) $itemsOnPage = $this->getDefaultItemsOnPage();
        if ($currentPage < 1) $currentPage = 1;

        $this->itemsOnPage = $itemsOnPage;
        $this->currentPage = $currentPage;
        $this->totalItems = null;
    }

    /**
     * @return Pageouter
     */
    public static function createSingleItem() { return new self(1,1); }

    /**
     * @return Pageouter
     */
    public static function createLastItems($num) { return new Pageouter(1,$num); }

    /**
     * @return Pageouter
     */
    public static function createFromRequest($defaultItemsOnPage = null) {

        if ($defaultItemsOnPage === self::UNLIMITED)
            return new FakePageouter();

        $currentPage = Form::getIntAnyway('page');
        $itemsOnPageFromUser = Form::getIntAnyway('itemsOnPage');

        if ($itemsOnPageFromUser) {
            $itemsOnPage = $itemsOnPageFromUser;
        } else if ($defaultItemsOnPage !== null) {
            $itemsOnPage = $defaultItemsOnPage;
        } else {
           $itemsOnPage = 0;
        }

        return new self($currentPage, $itemsOnPage);
    }

    /**
     * @return Diapasone
     */
    public function getDiapasone() {
        return Diapasone::createFromNum(
            ($this->currentPage - 1) * ($this->itemsOnPage),
            $this->itemsOnPage
        );
    }

    public function setTotalItems($num) {
        $this->totalItems = (int) $num;
    }

    public function getNumPages() {

        if ($this->totalItems === null)
            throw new Exception('TotalItems number undefined');

        return ceil($this->totalItems / $this->itemsOnPage);
    }

    public function exportToHash() {
        return array(
            'current'  => $this->currentPage,
            'numpages' => $this->getNumPages(),
            'pageVarname' => 'page',
        );
    }
}

class FakePageouter extends Pageouter {

    public function __construct() {}

    /**
     * @return Diapasone
     */
    public function getDiapasone() {
        return Diapasone::createUnlimited();
    }

    public function setTotalItems($num) {}

    public function getNumPages() { return 1; }

    public function exportToHash() {
        return array(
            'current'  => 1,
            'numpages' => $this->getNumPages(),
            'pageVarname' => 'page',
        );
    }
}

?>